package activity.video.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.hichip.callback.PlayLocalFileCallback;
import com.hichip.campro.R;
import com.hichip.sdk.PlayLocal;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import activity.video.VideoActivity;
import bean.MyCamera;
import bean.VideoInfo;
import common.HiDataValue;
import custom.dialog.NiftyDialogBuilder;
import utils.HiToast;
import utils.HiTools;
import utils.SharePreUtils;

/**
 * Created by lt on 2018\3\1 0001.
 */

public class VideoInfoAdapter extends BaseAdapter implements PlayLocalFileCallback {
    private List<VideoInfo> video_list = new ArrayList<VideoInfo>();
    private Context mContext;
    private boolean isDeleteMode = false;
    private long mFirstTime = 0;
    protected File mConverFile;
    private MyCamera mMycamera;
    public PlayLocal mPlayLocal;
    private String absolutePath;
    private PopupWindow mPopupWindow;
    private TextView mTvCancel, mTvTransRote;
    private SeekBar mSeekBarTrans;
    private SimpleDateFormat sdf = new SimpleDateFormat("00:mm:ss");


    public VideoInfoAdapter(Context context, List<VideoInfo> video_list, MyCamera camera) {
        this.mContext = context;
        this.video_list = video_list;
        this.mMycamera = camera;
        mPlayLocal = new PlayLocal();
    }

    public int getCount() {
        return video_list.size();
    }

    public Object getItem(int position) {
        return video_list.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    @SuppressLint("InflateParams")
    public View getView(final int position, View convertView, ViewGroup parent) {
        final VideoInfo vi = video_list.get(position);
        if (vi == null) return null;
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = View.inflate(mContext, R.layout.list_video_local, null);
            holder = new ViewHolder();
            holder.cb_check = convertView.findViewById(R.id.cb_check);
            holder.txt_time = convertView.findViewById(R.id.txt_time);
            holder.iv_thumbnail = convertView.findViewById(R.id.iv_thumbnail);
            holder.iv_icon_download = convertView.findViewById(R.id.iv_icon_download);
            holder.size = convertView.findViewById(R.id.txt_size);
            holder.ivTranscord = convertView.findViewById(R.id.iv_transcoding);

            holder.tv_video_type = convertView.findViewById(R.id.tv_video_type);
            holder.tv_video_duration = convertView.findViewById(R.id.tv_video_duration);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.cb_check.setChecked(vi.isChecked() ? true : false);
        holder.iv_icon_download.setVisibility(vi.getType() == 1 ? View.GONE : View.VISIBLE);
        String path = "";
        if (vi.getType() == 1) {//录制的
            File file = new File(HiDataValue.getPathCameraLocalRecordSnapShot(mMycamera.getUid(),mContext) + vi.getFilename());
            Glide.with(mContext).load(file).error(R.mipmap.online).into(holder.iv_thumbnail);
            path = HiDataValue.getPathCameraVideoLocalRecord(mMycamera.getUid(),mContext) + vi.getFilename();
            holder.tv_video_type.setText(mContext.getString(R.string.hand_video));
        } else {
            holder.iv_thumbnail.setImageResource(R.mipmap.online);
            path = HiDataValue.getPathCameraVideoOnLineDownLoad(mMycamera.getUid(),mContext) + vi.getFilename();
            String[] strings = vi.getFilename().split("\\.");
            int state = SharePreUtils.getInt(HiDataValue.CACHE, mContext, strings[0]);
            final String[] mTextArray = mContext.getResources().getStringArray(R.array.online_recording_type);
            if (state >= 0 && state <= 3) {
                holder.tv_video_type.setText(mTextArray[state]);
            }else {
                holder.tv_video_type.setText(mTextArray[3]);
            }
        }
        if (mPlayLocal != null) {
            Date date = new Date(mPlayLocal.GetFileTime(path) * 1000);
            holder.tv_video_duration.setText(sdf.format(date));
        }

        holder.cb_check.setVisibility(isDeleteMode ? View.VISIBLE : View.GONE);
        holder.txt_time.setText(vi.start_time);
        holder.size.setText(HiTools.formetFileSize(vi.fileLen));
        final String[] strings = vi.filename.split("\\.");

        holder.ivTranscord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mFirstTime = 0;
                if (strings.length > 1) {
                    if ("h264".equalsIgnoreCase(strings[1]) || "avi".equalsIgnoreCase(strings[1])) {
                        if (vi.getType() == 0) {
                            absolutePath = HiDataValue.getPathCameraVideoOnLineDownLoad(mMycamera.getUid(),mContext);
                        }
                        if (mPlayLocal != null) {
                           mPlayLocal.registerPlayLocalStateListener(VideoInfoAdapter.this::callbackplaylocal);
                        }
                        transDialogshow(vi);
                    } else {
                        //本地录像MP4 文件转换至相册
                        if (vi.getType() == 1) {
                            absolutePath = HiDataValue.getPathCameraVideoLocalRecord(mMycamera.getUid(),mContext);
                        }
                        DumpDialogshow(vi);
                    }
                }
            }
        });
        return convertView;
    }

    protected void transDialogshow(final VideoInfo vi) {
        View customView = View.inflate(mContext, R.layout.dialog_transcord, null);
        final PopupWindow popupWindow = new PopupWindow(customView);
        ColorDrawable cd = new ColorDrawable(-000);
        popupWindow.setBackgroundDrawable(cd);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);
        customView.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        customView.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                if (HiTools.isSDCardExist()) {
                    String[] strings = vi.filename.split("\\.");
                    File folderFiel = new File(HiDataValue.LOCAL_CONVERT_PATH + mMycamera.getUid() + "/");

                    if (!folderFiel.exists()) {
                        folderFiel.mkdirs();
                    }
                    mConverFile = new File(folderFiel.getAbsolutePath() + "/" + strings[0] + ".mp4");
                    if (!mConverFile.exists()) {
                        try {
                            mConverFile.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        HiToast.showToast(mContext, mContext.getString(R.string.file_alearly_convert));
                        return;
                    }
                    Log.i("tedu","--mPlayLocal--:"+mPlayLocal);
                    if(mPlayLocal!=null){
                        int b = mPlayLocal.Start2Mp4(absolutePath + vi.filename, mConverFile.getAbsolutePath());
                    }else {
                        mPlayLocal=new PlayLocal();
                        mPlayLocal.registerPlayLocalStateListener(VideoInfoAdapter.this::callbackplaylocal);
                        int b = mPlayLocal.Start2Mp4(absolutePath + vi.filename, mConverFile.getAbsolutePath());
                    }
                }
            }
        });
    }


    protected void DumpDialogshow(final VideoInfo vi) {
        final NiftyDialogBuilder dialog = NiftyDialogBuilder.getInstance(mContext);
        dialog.isCancelable(false).withTitle(mContext.getString(R.string.to_album)).withMessage(mContext.getString(R.string.tint_to_album)).withButton1Text(mContext.getString(R.string.cancel)).withButton2Text(mContext.getString(R.string.sure)).setButton1Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        }).setButton2Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                final File file = new File(HiDataValue.LOCAL_CONVERT_PATH + mMycamera.getUid() + "/", vi.filename);
                if (HiTools.isSDCardExist() && file.exists()) {
                    HiToast.showToast(mContext, mContext.getString(R.string.file_alearly_convert));
                    return;
                }
                if (mContext instanceof VideoActivity) {
                    VideoActivity act = (VideoActivity) mContext;
                    act.showjuHuaDialog();
                }
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                // 文件拷贝到convert文件夹
                if (file.isFile() && file.exists()) {
                    file.delete();
                }
                new Thread() {
                    public void run() {
                        copyFile(absolutePath + vi.filename, file.getAbsolutePath());
                        Message msg = Message.obtain();
                        msg.obj = file;
                        msg.what = 0X888;
                        mHandler.sendMessage(msg);
                    }

                    ;
                }.start();

            }
        });
        dialog.show();

    }

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { // 文件存在时
                InputStream inStream = new FileInputStream(oldPath); // 读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; // 字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    public void unRegister() {
        if (mPlayLocal != null) {
            mPlayLocal.unregisterPlayLocalStateListener(this);
            mPlayLocal.Stop2Mp4();
        }
        if (mPopupWindow != null) {
            mPopupWindow.dismiss();
        }
    }


    public boolean isDeleteMode() {
        return isDeleteMode;
    }

    public void setDeleteMode(boolean deleteMode) {
        isDeleteMode = deleteMode;
    }

    // 文件转码的回调

    /**
     * 视频宽，高，文件时长 ，文件播放进度，音频类型，播放状态
     */
    @Override
    public void callbackplaylocal(int width, int height, int filetime, long cursec, int audiotype, int state) {
        Message message = Message.obtain();
        switch (state) {
            case PlayLocalFileCallback.LOCAL2MP4_STATE_OPEN:
                message.what = PlayLocalFileCallback.LOCAL2MP4_STATE_OPEN;
                message.arg1 = filetime;
                mHandler.sendMessage(message);
                // showTransPupwindow();
                break;
            case PlayLocalFileCallback.LOCAL2MP4_STATE_ING:
                // if (cursec > 0) {
                if (mFirstTime == 0) {
                    mFirstTime = cursec;
                }
                int sub = (int) (cursec - mFirstTime);
                // if (sub > 0) {
                message.what = PlayLocalFileCallback.LOCAL2MP4_STATE_ING;
                message.arg1 = sub;
                message.arg2 = filetime;
                mHandler.sendMessage(message);
                // }
                // }
                break;
            case PlayLocalFileCallback.LOCAL2MP4_STATE_END:
                mPlayLocal.Stop2Mp4();
                mHandler.sendEmptyMessage(PlayLocalFileCallback.LOCAL2MP4_STATE_END);
                // 发通知图库更新文件显示
                Uri localUri = Uri.fromFile(mConverFile);
                Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
                mContext.sendBroadcast(localIntent);
                break;
            case PlayLocalFileCallback.LOCAL2MP4_STATE_ERROR:
                HiToast.showToast(mContext, mContext.getString(R.string.data_parsing_error));
                break;
        }

    }

    public final class ViewHolder {
        public CheckBox cb_check;
        public ImageView iv_thumbnail;
        public ImageView iv_icon_download;
        public TextView txt_time;
        public TextView size;
        public ImageView ivTranscord;
        public TextView tv_video_type;
        public TextView tv_video_duration;
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0X888:
                    File file = (File) msg.obj;
                    if (file != null && file.exists() && file.isFile()) {
                        Uri localUri = Uri.fromFile(file);
                        Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
                        mContext.sendBroadcast(localIntent);
                        if (mContext instanceof VideoActivity) {
                            VideoActivity act = (VideoActivity) mContext;
                            act.dismissjuHuaDialog();
                        }
                        HiToast.showToast(mContext, mContext.getString(R.string.success_to_album));
                    }
                    break;
                case PlayLocalFileCallback.LOCAL2MP4_STATE_OPEN:
                    showTransPupwindow(msg.arg1);
                    break;
                case PlayLocalFileCallback.LOCAL2MP4_STATE_ING:
                    int sub = msg.arg1;
                    int fileTime = msg.arg2;
                    int rate = (int) Math.round((double) sub / 1000 / fileTime * 100);
                    if (rate < 100) {
                        mTvTransRote.setText(rate + "%");
                    }
                    mSeekBarTrans.setProgress(sub);
                    break;
                case PlayLocalFileCallback.LOCAL2MP4_STATE_END:
                    mTvTransRote.setText("100%");
                    mTvCancel.setText(mContext.getString(R.string.finish));
                    break;
                case PlayLocalFileCallback.LOCAL2MP4_STATE_ERROR:
                    HiToast.showToast(mContext, mContext.getString(R.string.data_parsing_error));
                    if (mConverFile != null && mConverFile.exists()) {
                        mConverFile.delete();
                    }
                    break;

            }

        }

        ;
    };

    private void showTransPupwindow(int filetime) {
        View customView = View.inflate(mContext, R.layout.dialog_trans_pro, null);
        mPopupWindow = new PopupWindow(customView);
        ColorDrawable cd = new ColorDrawable(-000);
        mPopupWindow.setBackgroundDrawable(cd);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        mPopupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        mPopupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);
        // 取消
        mTvCancel = (TextView) customView.findViewById(R.id.tv_cancel);
        mTvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
            }
        });

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                if (mContext.getString(R.string.cancel).equals(mTvCancel.getText().toString())) {
                    mPlayLocal.Stop2Mp4();
                    // 删除文件
                    if (mConverFile.exists()) {
                        mConverFile.delete();
                    }
                }

            }
        });
        mTvTransRote = (TextView) customView.findViewById(R.id.rate_loading_trances);
        mSeekBarTrans = (SeekBar) customView.findViewById(R.id.sb_transd_video);
        mSeekBarTrans.setMax(filetime * 1000);
    }

    public Bitmap getVideoThumbnail(String videoPath) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(videoPath);
        Bitmap bitmap = media.getFrameAtTime();
        return bitmap;
    }
}
